<?php
namespace control;
/*
* 车辆费用类
*/

class carFeeClass extends adIndexClass
{
    private const page = 'carFee';
    private const title = '车辆费用';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'costDate'      => [
                        'name'  => "报销日期",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'fileBtn' => [
                        'name'  => "附件",
                        'width' => 120,
                    ],
                    'carNo'  => [
                        'name'  => "车牌号",
                        'width' => 120,
                    ],
                    'costType'         => [
                        'name'  => '报销类型',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '费用类型',
                        'width' => 120,
                    ],
                    'applyDate'    => [
                        'name'  => '发生日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'money'    => [
                        'name'  => '费用金额（'.static::$unit.'）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'text'    => [
                        'name'  => '费用说明',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'    => [
                        'name'  => '报销人',
                        'width' => 120,
                    ],
                    'deptName'    => [
                        'name'  => '报销人部门',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '审批状态',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'isPay'    => [
                        'name'  => '拨付状态',
                        'width' => 120,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "报销人部门" => text(array("name" => "deptName")),
                    "费用类型"     => select(["name" => "costType", 'option' => explode('，', para('costType'))]),
                    "审批状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ],
                [
                    '拨付状态'   => select(array("name" => "isPay", "option" => ['是','否'])),
                    "发生日期" => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "报销日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.deptName" => $this->post('deptName'),
        );
        //全等查询数组
        $equal = array(
            'a.type'=>'车辆费用',
            "a.state" => $this->post('state'),
            "b.type" => $this->post('costType'),
        );
        $and   = "";
        if ($this->post('isPay') =='是'){
            $and.=" and isPay = 1";
        }elseif($this->post('isPay') =='否'){
            $and.=" and isPay = 0";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'a.time');
        }
        if ($this->post('recordDate')) {
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'b.applyDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'applyDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //查看自己
        $and .= $this->seeSelf(self::page, 'a.stid');
        //获取查询结果
        $where                         = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page([
            "field"=>"b.*,date(a.time) as costDate,a.type as costType,a.state,a.isPay,a.stid,a.deptName,a.targetId",
            "table" => "cost as a join cost_record as b on a.id = b.costId",
            "where" => $where,
            "order" => $orderBy['orderBy'],
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "detail" => array("title" => "费用报销详情", "click" => "newIframe('费用报销详情','" . root . "control/adIndex.html?cla=cost&fun=detail&id=" . $array['costId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "fileBtn":
                        $num = static::total(array('table' => 'file', 'where' => "targetId = '" . $array['id'] . "'"));
                        $fileBtn = $num > 0 ? "<span style='cursor: pointer;color: #629afd' onclick=\"layer('car','fileDetail',{id:'" . $array['id'] . "',type:'费用报销'})\">" . $num . "</span>" : '';
                        $row[] = $fileBtn;
                        break;
                    case "carNo":
                        $car = query('car',"id = '$array[targetId]'");
                        $row[] = $car['shortName'].$car['carNo'];
                        break;
                    case "isPay":
                        $row[] = $array['isPay']?'是':'否';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "cost as a join cost_record as b on a.id = b.costId",
            'single' => $where,
            'field'  => "ifnull(sum(b.money),0) as money",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 费用汇总导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "field"=>"b.*,date(a.time) as costDate,a.type as costType,a.state,a.isPay,a.stid,a.deptName,a.targetId",
                    "table" => "cost as a join cost_record as b on a.id = b.costId",
                    "where" => "b.id in ('".implode("','", $checkedId)."') order by applyDate desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $car = query('car',"id = '$array[targetId]'");
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '报销日期'=>$array['costDate'],
                            '车牌号'=>$car['shortName'].$car['carNo'],
                            '报销类型'=>$array['costType'],
                            '费用类型'=>$array['type'],
                            '发生日期'=>$array['applyDate'],
                            '费用金额'=>$array['money'],
                            '费用说明'=>$array['text'],
                            '报销人'=>self::findStaff($array['stid']),
                            '报销人部门'=>$array['deptName'],
                            '审批状态'=>$array['state'],
                            '拨付状态'=>$array['isPay']?'是':'否',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了车辆费用汇总";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "车辆费用汇总.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'报销日期',
                    'aliasName'=>'报销日期',
                ],
                [
                    'columnName'=>'车牌号',
                    'aliasName'=>'车牌号',
                ],
                [
                    'columnName'=>'报销类型',
                    'aliasName'=>'报销类型',
                ],
                [
                    'columnName'=>'费用类型',
                    'aliasName'=>'费用类型',
                ],
                [
                    'columnName'=>'发生日期',
                    'aliasName'=>'发生日期',
                ],
                [
                    'columnName'=>'费用金额',
                    'aliasName'=>'费用金额',
                ],
                [
                    'columnName'=>'费用说明',
                    'aliasName'=>'费用说明',
                ],
                [
                    'columnName'=>'报销人',
                    'aliasName'=>'报销人',
                ],
                [
                    'columnName'=>'报销人部门',
                    'aliasName'=>'报销人部门',
                ],
                [
                    'columnName'=>'审批状态',
                    'aliasName'=>'审批状态',
                ],
                [
                    'columnName'=>'拨付状态',
                    'aliasName'=>'拨付状态',
                ],
            ]
        };
    }
}

